use axum::{
    http::StatusCode,
    response::{IntoResponse, Response},
    Json,
};

use serde_json::json;

#[derive(Debug,thiserror::Error)]
pub enum AppError {
    #[error("数据库错误：{0}")]
    DatabaseError(#[from] sqlx::Error),

    #[error("内部服务器错误：{0}")]
    InternalServerError(String),


    #[error("请求参数错误：{0}")]
    BadRequest(String),


    #[error("未授权：{0}")]
    Unauthorized(String),
}

impl IntoResponse for AppError { 
    fn into_response(self) -> Response { 
        let (status, error_message) = match self {
            AppError::DatabaseError(_) => (StatusCode::INTERNAL_SERVER_ERROR, "数据库错误".to_string()),
            AppError::InternalServerError(_) => (StatusCode::INTERNAL_SERVER_ERROR, "内部服务器错误".to_string()),
            AppError::BadRequest(message) => (StatusCode::BAD_REQUEST, message),
            AppError::Unauthorized(_) => (StatusCode::UNAUTHORIZED, "未授权".to_string()),
        };

        let body = Json(json!({
            "error": error_message,
        }));

        (status, body).into_response()
    }
}